//
//  ETComplaintViewController.swift
//  mggz
//
//  Created by QinWei on 2018/5/21.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit

class ETComplaintViewController: UIViewController {
    fileprivate var coverView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        return view
    }()
    
    fileprivate lazy var panelView:WorkerSalaryPreView = {
        let view = WorkerSalaryPreView.init(frame: CGRect.zero)
        
        return view
    }()
    fileprivate lazy var secondPanelView:WorkerSalaryTPreView = {
        let view = WorkerSalaryTPreView.init(frame: CGRect.zero)

        return view
    }()
    private var okHandler: (()->Void)?
    private var message: [String: Any]?
    fileprivate var bodyTitle: String?
    fileprivate var realPaySalaryStr:String?
    fileprivate var protocolSalaryStr:String?
    fileprivate var reasonStr:String?
    //当前alert是否正在显示
    private var isShowing:Bool = false
    init (_ message: [String: Any],dict:[String: Any], okHandler: @escaping ()-> Void){
        super.init(nibName: nil, bundle: nil)
        self.transitioningDelegate = self
        self.okHandler = okHandler
        self.message = message
        
        realPaySalaryStr = message["RealPaySalary"] as? String
        protocolSalaryStr = message["ProtocolSalary"] as? String
        reasonStr = message["DeductionReason"] as? String
        self.bodyTitle = dict["body"] as? String
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.clear

        self.updateViews()
        
        self.isShowing = true
    }
    deinit {
        self.isShowing = false
    }
    
    fileprivate func setupUIView(){
        self.view.addSubview(self.coverView)
        self.coverView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        let changeState = self.message!["ChangeState"] as? String
        if changeState == "111" || changeState == "110" || changeState == "101"{
            self.panelView.companyLabel.text = self.bodyTitle
            self.panelView.realSalary.text = self.realPaySalaryStr! + "元"
            self.panelView.protocolSalary.text = self.protocolSalaryStr! + "元"
            self.panelView.reasonLabel.text = reasonStr
            self.panelView.companyLabel.sizeToFit()
            self.panelView.reasonLabel.sizeToFit()
            if changeState == "111"{
                self.panelView.appealButton.setTitle("投诉", for: .normal)
            self.panelView.appealButton.setTitleColor(UIColor.init(white: 102/255.0, alpha: 1), for: .normal)
            }else if changeState == "110"{
                self.panelView.appealButton.setTitle("投诉", for: .normal)
            self.panelView.appealButton.setTitleColor(UIColor.init(red: 0.96, green: 0.65, blue: 0.14, alpha: 1), for: .normal)
            }else if changeState == "101"{
                
                
            self.panelView.appealButton.setTitle("投诉", for: .normal)
        self.panelView.appealButton.setTitleColor(UIColor.init(red: 0.96, green: 0.65, blue: 0.14, alpha: 1), for: .normal)
                
            }
            self.view.addSubview(self.panelView)
            let topH = self.panelView.companyLabel.frame.height + self.panelView.reasonLabel.frame.height + 375
            print(topH)
            self.panelView.snp.makeConstraints { (make) in
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.centerY.equalTo(self.view)
                make.height.equalTo(topH)
            }
            self.panelView.agreeButton.addTarget(self, action: #selector(doLeftButtonAction), for: .touchUpInside)
            
        }else if changeState == "001" || changeState == "011" || changeState == "010"{
            
            self.secondPanelView.companyName.text = self.bodyTitle
            self.secondPanelView.realSalary.text = self.realPaySalaryStr! + "元"
            self.secondPanelView.procotolSalary.text = self.protocolSalaryStr! + "元"
            self.secondPanelView.companyName.sizeToFit()
            
            self.view.addSubview(self.secondPanelView)
            let topH = self.secondPanelView.companyName.frame.height + 349
            
            if changeState == "001"{
              self.secondPanelView.appealButton.setTitle("投诉", for: .normal)
            self.secondPanelView.appealButton.setTitleColor(UIColor.init(red: 0.96, green: 0.65, blue: 0.14, alpha: 1), for: .normal)
            }else if changeState == "011"{
                self.secondPanelView.appealButton.setTitle("投诉", for: .normal)
                self.secondPanelView.appealButton.setTitleColor(UIColor.init(white: 102/255.0, alpha: 1), for: .normal)
            }else if changeState == "010"{
                self.secondPanelView.appealButton.setTitle("投诉", for: .normal)
            self.secondPanelView.appealButton.setTitleColor(UIColor.init(red: 0.96, green: 0.65, blue: 0.14, alpha: 1), for: .normal)
            }
            
            self.secondPanelView.snp.makeConstraints { (make) in
                make.left.equalTo(20)
                make.right.equalTo(-20)
                make.centerY.equalTo(self.view)
                make.height.equalTo(topH)
            }
          self.secondPanelView.agreeButton.addTarget(self, action: #selector(doLeftButtonAction), for: .touchUpInside)
        }
    }
    
    
    
    private func updateViews() {
       
    }
    
    @objc private func doLeftButtonAction() {
        
        let alert = UIAlertController(title: "监管部门将会收到您的相关投诉，如果恶意投诉，将有可能会被行政处罚！", message: "", preferredStyle: .alert)
        let refuseApp = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
            // self.dismiss(animated: true, completion: nil)
            
        })
        let gotoAppstore = UIAlertAction(title: "坚持投诉", style: .default, handler: { (action) in
            self.dismiss(animated: true, completion: nil)
            //self.setWorkerSalaryAdvanceConsult(2)
        })
        alert.addAction(gotoAppstore)
        alert.addAction(refuseApp)
        self.present(alert, animated: true, completion: {
            
        })
    }
    @objc private func doLeftButtonAction2() {
        
        let alert = UIAlertController(title: "您的工资发放金额符合您的考勤统计，确认要申诉吗？恶意协商将影响您的个人信誉!", message: "", preferredStyle: .alert)
        let refuseApp = UIAlertAction(title: "取消", style: .cancel, handler: { (action) in
            // self.dismiss(animated: true, completion: nil)
            
        })
        let gotoAppstore = UIAlertAction(title: "坚持申诉", style: .default, handler: { (action) in
            self.dismiss(animated: true, completion: nil)
           // self.setWorkerSalaryAdvanceConsult(2)
        })
        alert.addAction(gotoAppstore)
        alert.addAction(refuseApp)
        self.present(alert, animated: true, completion: {
            
        })
        
    }
    @objc private func doRightButtonAction() {
        //self.setWorkerSalaryAdvanceConsult(1)
        if self.okHandler != nil {
            self.okHandler!()
        }
        self.dismiss(animated: true, completion: nil)
    }
    
    fileprivate func setupComplaintResult(_ sort:Int){
            guard let accountId = WWUser.sharedInstance.accountId else{
            return
            }
            guard let advanceDetailID = self.message!["AdvanceDetailID"] as? String else {
            return
            }
    LCAPiSubManager.request(.SetWorkerSalaryAdvanceConfirmResult(advanceDetailID: advanceDetailID, confirmResult: sort, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
            guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
            return
            }

            guard (jsonString["State"]) as! String == "OK" else{

            return
            }
            WWSuccess("保存成功!")
            }
            }
       }
}
extension ETComplaintViewController: UIViewControllerTransitioningDelegate {
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return ComplaintViewControllerTransitionPresent()
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return ComplaintViewControllerTransitionDismiss()
    }
}

class ComplaintViewControllerTransitionPresent: NSObject, UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromView = transitionContext.view(forKey: .from)
        let toVc = transitionContext.viewController(forKey: .to) as! ETComplaintViewController
        let container = transitionContext.containerView
        container.addSubview(toVc.view)
        
        let panelView = toVc.panelView
        let coverview = toVc.coverView
        coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        panelView.alpha = 0.3
        panelView.transform = CGAffineTransform.init(scaleX: 1.3, y: 1.3)
        UIView.animate(withDuration:0.1, animations: {
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.3)
            panelView.transform = CGAffineTransform.identity
            panelView.alpha = 1
        }) { (finish) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
            toVc.view.addSubview(fromView!)
            toVc.view.sendSubview(toBack: fromView!)
        }
    }
}

class ComplaintViewControllerTransitionDismiss: NSObject,UIViewControllerAnimatedTransitioning {
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.1
    }
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
        let fromVc = transitionContext.viewController(forKey: .from) as! ETComplaintViewController
        
        //        let panelView = fromVc.panelView
        let coverview = fromVc.coverView
        UIView.animate(withDuration: 0.1, animations: {
            coverview.backgroundColor = UIColor.black.withAlphaComponent(0.01)
        }) { (_) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    }
}
